package com.time.on.device.activity;

import java.text.ParseException;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.time.on.device.R;
import com.time.on.device.helper.TimeHelper;
import com.time.on.device.model.DataConfig;
import com.time.on.device.service.TimerService;

public class TimeConfigActivity extends BaseTimeActivity {

	private TextView textViewRemainTime;
	private long millisInfuture;
	static final int TIME_DIALOG_ID = 123;
	private CountDown countDown;
	private boolean isStarted = false;
	private DataConfig dataConfig;
	private Boolean isCreated = false;
	private AdView adView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.time_config_activity);
		// Create an ad
		adView = (AdView) findViewById(R.id.adView);
		if (isNetworkConnected()) {
			AdRequest adRequest = new AdRequest.Builder().build();
			adView.loadAd(adRequest);
		} else {
			adView.setVisibility(View.GONE);
		}
		//
		dataConfig = new DataConfig(this);
		this.setUpTimeConfig();
		isStarted = dataConfig.getCurrentStatus();
		if (isStarted) {
			continueRunWithRemainTime();
		}
		// Clear notification if have any
		TimerService.clearNotification(this);
		isCreated = true;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (adView != null) {
			adView.resume();
		}
		if (isStarted) {
			if (!isCreated) {
				continueRunWithRemainTime();
			} else {
				isCreated = false;
			}
		}

	}	

	@Override
	public void onPause() {
		if (adView != null) {
			adView.pause();
		}
		super.onPause();
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}

	private TimePickerDialog.OnTimeSetListener timeSetListener = new OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			millisInfuture = TimeHelper.timeToMilis(hourOfDay, minute);
			displayTimeSet(millisInfuture);
			dataConfig.saveTimeConfig(millisInfuture);
			// reset count down if already started
			if (isStarted) {
				toggleStartStop();// Stop count
			}

		}
	};

	@Override
	public void finish() {

		super.finish();
		stopCountDown();
		saveConfiguration();

	}

	private void continueRunWithRemainTime() {

		if (TimerService.timeRemain > 0) {
			// That means service is running, no need to call start serive
			millisInfuture = TimerService.timeRemain;
		} else {
			millisInfuture = dataConfig.getTimeConfig();
			// That means service is not running
			startTimerService();
		}
		startCountDown();
		setStartStopButton();

	}

	private void saveConfiguration() {
		// Keep status of service is started or stopped
		dataConfig.saveCurrentStatus(isStarted);
		// Check and save configuration
		checkAndSaveMessageConfig();
		saveIsLocked();
	}

	// Create time set dialog
	@Override
	protected Dialog onCreateDialog(int id) {
		if (TIME_DIALOG_ID == id) {
			return new TimePickerDialog(this, timeSetListener, HOURS_DEFAULT,
					MINUTES_DEFAULT, true);
		} else {
			return null;
		}

	}

	private void displayTimeSet(long timeToDislay) {
		try {

			String hms = TimeHelper.timeToString(timeToDislay);
			textViewRemainTime.setText(hms);
		} catch (ParseException e) {
			Log.e(ERROR_TAG, "Fail to parse time to string", e);
		}
	}

	private void setUpTimeConfig() {
		textViewRemainTime = (TextView) findViewById(R.id.tvRemainTime);
		// Get configuration time
		if (dataConfig.getTimeConfig() > 0) {
			millisInfuture = dataConfig.getTimeConfig();
			displayTimeSet(millisInfuture);
		} else {
			millisInfuture = TimeHelper.timeToMilis(HOURS_DEFAULT,
					MINUTES_DEFAULT);
			textViewRemainTime.setText(TIME_DEFAULT);
		}
		// Set confirm message
		EditText editTextInform = (EditText) findViewById(R.id.editTextInformMessage);
		editTextInform.setText(dataConfig.getMessageConfig());
		// Is locked screen
		CheckBox chkLockScreen = (CheckBox) findViewById(R.id.chkLockScreen);
		chkLockScreen.setChecked(dataConfig.isLockedScreen());

		// Add event for button
		Button btnStart = (Button) findViewById(R.id.btnStart);
		btnStart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toggleStartStop();
				saveConfiguration();
			}
		});

		Button btnSet = (Button) findViewById(R.id.btnSetTime);
		btnSet.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});

	}

	private void checkAndSaveMessageConfig() {

		EditText editTextInform = (EditText) findViewById(R.id.editTextInformMessage);
		String messageConfig = editTextInform.getText().toString();
		if (!messageConfig.equalsIgnoreCase(dataConfig.getMessageConfig())) {
			dataConfig.saveMessageConfig(messageConfig);
		}

	}

	private void setStartStopButton() {
		Button btnStart = (Button) findViewById(R.id.btnStart);
		if (isStarted) {
			btnStart.setText(getResources().getString(R.string.stop));
		} else {
			btnStart.setText(getResources().getString(R.string.start));
		}

	}

	private void toggleStartStop() {
		if (!isStarted) {
			startCountDown();
			startTimerService();
			isStarted = true;

		} else {
			stopCountDown();
			stopTimerService();
			isStarted = false;
			displayTimeSet(millisInfuture);
		}
		setStartStopButton();
	}

	private void startCountDown() {
		// Stop current instance if already have
		stopCountDown();
		// Then create a new instance to start count down
		countDown = new CountDown(millisInfuture, INTERVAL_COUNT_DOWN);
		countDown.start();

	}

	private void stopCountDown() {

		// Stop current instance
		if (countDown != null) {
			countDown.cancel();
		}

	}

	private void startTimerService() {

		if (TimerService.timeRemain > 0) {
			// If the old is running so that stop it first
			stopService(new Intent(this, TimerService.class));
		}
		startService(new Intent(this, TimerService.class));

	}

	private void stopTimerService() {
		TimerService.timeRemain = 0;
		stopService(new Intent(this, TimerService.class));
	}

	private void saveIsLocked() {
		CheckBox chkLockScreen = (CheckBox) findViewById(R.id.chkLockScreen);

		Boolean bValueOfConfig = Boolean.valueOf(dataConfig.isLockedScreen());
		Boolean bValueOfCheckBox = Boolean.valueOf(chkLockScreen.isChecked());

		// If have changes then save
		if (bValueOfConfig.compareTo(bValueOfCheckBox) != 0) {
			dataConfig.saveIsLocked(chkLockScreen.isChecked());
		}
	}

	public class CountDown extends CountDownTimer {

		public CountDown(long millisInfuture, long countDownInterval) {
			super(millisInfuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			// Reset count down
			millisInfuture = dataConfig.getTimeConfig();
			startCountDown();
		}

		@Override
		public void onTick(long millisUntilFinished) {
			long millis = millisUntilFinished;
			displayTimeSet(millis);
		}

	}

}
